#coding=utf-8
import datetime
import os
import traceback
import time

from loguru import logger
from playwright.sync_api import sync_playwright
import douyin.dou_yin_common as dou_yin_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def dy_main(host):
    try:
        # 记录日期的路经
        log_file = os.path.join(os.getcwd(), 'logs', f'{datetime.datetime.now().strftime("%Y-%m-%d")}-dy.txt')
        if not os.path.exists(log_file):
            logger.add(log_file)
        with sync_playwright() as playwright:
            dy_func = dou_yin_common.DY(host, playwright, 'mudi-key', False)
            account_list = dy_func.get_login_account()
            if len(account_list) > 0:
                store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
                for store_id in store_id_list:
                    has_store = False
                    try:
                        # 过滤出当前店铺所有任务
                        store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                        # 登录并选择店铺
                        dy_func.login(store_job_list[0])
                        logger.info("正在选择店铺：【{}】".format(store_job_list[0]['account']))
                        store_list = []
                        div_list = dy_func.page.query_selector_all('div')
                        for div in div_list:
                            class_name = div.get_attribute('class')
                            if class_name is not None and 'index_introName__' in class_name:
                                store_list.append(div)
                        for store in store_list:
                            if store.text_content() == store_job_list[0]['account']:
                                store.click()
                                time.sleep(5)
                                # self.wait(self.page)
                                logger.info("登录店铺...")
                                has_store = True
                                break
                        if not has_store:
                            message = f'店铺名称【{store_job_list[0]["account"]}】不存在'
                            logger.info(message)
                            log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                            dy_func.update_log(log_id_list, message)
                            dy_func.close()
                            continue
                        # 店铺任务按照周期分组
                        job_group = group_by_period(store_job_list)
                        for period, job_list in job_group.items():
                            logger.info(f'开始下载周期【{period}】的账单...')
                            dy_func.after_login_check_dialog()
                            param_list = []
                            file_list = []
                            for item in job_list:
                                if item['accountType'] == '结算账单':
                                    # 下载结算单流程
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_file = dy_func.download_bill(item, period, start_time)
                                    if bill_file is not None:
                                        if bill_file == -1:
                                            message = f'子账号没有权限'
                                            logger.info(message)
                                            log_id_list = [item['logId']]
                                            dy_func.update_log(log_id_list, message)
                                        else:
                                            file_list.append(bill_file)
                                            dir_path, file_name = os.path.split(bill_file)
                                            param_list.append({'orderType': '结算账单', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '结算账单', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '资金流水':
                                    # 下载资金流水流程
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_file = dy_func.download_fund_flow(item, period)
                                    if bill_file is not None:
                                        if bill_file == -1:
                                            message = f'子账号没有权限'
                                            logger.info(message)
                                            log_id_list = [item['logId']]
                                            dy_func.update_log(log_id_list, message)
                                        else:
                                            file_list.append(bill_file)
                                            dir_path, file_name = os.path.split(bill_file)
                                            param_list.append({'orderType': '资金流水', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '资金流水', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '结算账单总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = dy_func.get_bill_count(period)
                                    param_list.append({'orderType': '结算账单总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '资金流水总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = dy_func.get_fund_flow_count(period)
                                    param_list.append({'orderType': '资金流水总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            if len(param_list) > 0:
                                # 编码字符串
                                coding_param = dy_func.encode_param(param_list)
                                # 上传文件
                                uri = "api/v1/dyBill/dyBillRPAImport/{}".format(job_list[0]['storeCode'])
                                dy_func.upload_file(uri, coding_param, file_list)
                        dy_func.close()
                    except:
                        logger.info(traceback.format_exc())
                        dy_func.close()
    except:
        traceback.print_exc()